#!/bin/sh
# questo script divide file CUD prodotti da fantastico programma Teamsystem
FILE=$1
i=`pdfinfo $FILE | grep Pages | awk '{print $2}'`
echo $i

	echo "selezionato \"$FILE\""

                mkdir -p out
    		while (("$i">0)) 
    		do
			n=$(($i/4))	
    			gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -sColorConversionStrategy=RGB -dProcessColorModel=/DeviceRGB -dPDFSETTINGS=/prepress -dQUIET -dNOPAUSE -dBATCH -dSAFER -dFirstPage=$(($i-3)) -dLastPage=$i -sOutputFile=out/scp_$n.pdf $FILE 1>&2
			echo $n;
			fp="out/scp_$n.pdf"

			#fn1=`pdftotext $fp - | sed -n '273p'`
			#fn2=`pdftotext $fp - | sed -n '285p'`
    			#outFile="$n-$fn1 - $fn2"

			fn=`pdftotext $fp - |grep  -i "Cognome e Nome" | head -1 | awk '{print $7 " " $8 " " $9 " " $10}'`
			outFile="$n-$fn"
			echo $outFile
			mv "$fp" "out/$outFile.pdf"
    			i=$(($i-4)) 
    		done

#    		for fp in $(ls out/scp*.pdf)
#    		do
#			fn1=`pdftotext $fp - | sed -n '83p'`
#			fn2=`pdftotext $fp - | sed -n '98p'`
#			echo $fn1 $fn2
#    		        mv "$fp" "out/$fn1-$fn2.pdf"
#    		
#    		done
